package com.workpaper;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

import com.workpaper.app.db.mybatis.MyDB;
import com.workpaper.app.init.CacheInitor;
import com.workpaper.app.init.ConfigInitor;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

	@Override
	public Object start(IApplicationContext context) throws Exception {
		//加载资源
		resourceInit();
		
//		context.applicationRunning();	//关闭闪屏画面
		
//		LoginDialog loginDialog = new LoginDialog(null);
//		int result = loginDialog.open();
//		if(result != Window.OK) {
//			//登录失败，结束
//			return IApplication.EXIT_OK;
//		}
		Display display = PlatformUI.createDisplay();
		try {
			int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
			if (returnCode == PlatformUI.RETURN_RESTART) {
				return IApplication.EXIT_RESTART;
			}
			return IApplication.EXIT_OK;
		} finally {
			display.dispose();
			//关闭资源
			clearResource();
		}
		
	}
	
	/**
	 * 资源初始化，工作台启动之前调用
	 */
	private void resourceInit() {
		//加载配置信息
		ConfigInitor.loadConfig();
		//加载国际化资源
		CacheInitor.doResourceCache();
		//初始化数据源
		MyDB.initDB();
	}
	
	/**
	 * 清理资源，在关闭应用前调用
	 */
	private void clearResource() {
		MyDB.clearResource();
	}
	
	@Override
	public void stop() {
		if (!PlatformUI.isWorkbenchRunning())
			return;
		final IWorkbench workbench = PlatformUI.getWorkbench();
		final Display display = workbench.getDisplay();
		display.syncExec(() -> {
			if (!display.isDisposed())
				workbench.close();
		});
	}
}
